package model;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

//管理数据库连接
//1.建立连接
//2.断开连接
//单例模式来建立连接
public class DBUtil {
    private static DataSource dataSource = null;

    private static final String URL="jdbc:mysql://127.0.0.1:3306/blogDemo?characterEncoding=utf-8&useSSL=true";
    private static final String USERNAME="root";
    private static final String PASSWORD="1234";
    //建立连接
    public static DataSource getDataSource(){
        if(dataSource == null) {
            synchronized (DBUtil.class) {
                if (dataSource == null) {
                    dataSource = new MysqlDataSource();
                    //还需要给连接设置一些属性
                    ((MysqlDataSource)dataSource).setURL(URL);
                    ((MysqlDataSource)dataSource).setUser(USERNAME);
                    ((MysqlDataSource)dataSource).setPassword(PASSWORD);
                }
            }
        }
        return dataSource;
    }

    //获取连接
    public static Connection getConnection(){
        try {
            return getDataSource().getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    //断开连接
    public static void close(Connection connection, PreparedStatement statement,
                             ResultSet resultSet){

            try {
                if(resultSet != null) {
                    resultSet.close();
                }
                if(statement != null){
                    statement.close();
                }
                if(connection != null){
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

    }
}
